package com.lgkj.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.request.RequestOptions;
import com.lgkj.R;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.model.CropOptions;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;

/**
 * Created by Administrator on 2018/6/15 0015.
 */

public class CommonUtils {
    /*
    * @param context
    * @param imageView
    * @param url
    * @param imgId
    */
    public static void LoadImage(Context context, ImageView imageView, String url, int imgId) {
        if (context == null) {
            Log.e("Glide.load", "context  is  null: ");
            return;
        }
        if (url == null) {
            Log.e("Glide.load", "url  is  null: ");
            return;
        }
        if (url.contains("http:") || url.contains("https:")) {
        } else {
            url = "http:" + url;
        }
        Log.d("Glide.load", "LoadImage: " + url);
        RequestOptions options = new RequestOptions()
                .centerCrop().fitCenter()
                .placeholder(imgId)
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .error(R.mipmap.error); // “23”：设置模糊度(在0.0到25.0之;
        Glide.with(context).load(url).apply(options).into(imageView);
//        Glide.with(context).load(url).placeholder(imgId).error().into(imageView);
    }

    public static void LoadImage(Context context, ImageView imageView, File file, int imgId) {
        if (context == null) {
            return;
        }
        if (!file.exists()) {
            return;
        }
        Log.d("Glide.load", "LoadImage: " + file.getPath());
        RequestOptions options = new RequestOptions()
                .centerCrop().fitCenter()
                .placeholder(imgId)
                .skipMemoryCache(true)
                .error(R.mipmap.error);
//                .priority(Priority.HIGH);
        Glide.with(context).load(file).apply(options).into(imageView);
    }

    public static void loadImageRound(Context context, ImageView imageView, String url, int imgId) {
        if (context == null) {
            return;
        }
        if (url == null) {
            return;
        }
        if (url.contains("http:") || url.contains("https:")) {
        } else {
            url = "http:" + url;
        }
        Log.d("Glide.load", "LoadImage: " + url);
        RequestOptions options = new RequestOptions()
                .centerCrop().fitCenter().skipMemoryCache(true)
                .placeholder(imgId).bitmapTransform(new BitmapTransformation() {
                    @Override
                    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
                        return null;
                    }

                    @Override
                    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

                    }
                }).circleCrop()
                .error(R.mipmap.error);
//                .priority(Priority.HIGH);
        Glide.with(context).load(url).apply(options).into(imageView);
    }

    public static void loadImageRound(Context context, ImageView imageView, File file, int imgId) {
        if (context == null) {
            return;
        }
        if (!file.exists()) {
            return;
        }
        Log.d("Glide.load", "LoadImage: " + file.getPath());
        RequestOptions options = new RequestOptions()
                .centerCrop().fitCenter().skipMemoryCache(true)
                .placeholder(imgId).bitmapTransform(new BitmapTransformation() {
                    @Override
                    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
                        return null;
                    }

                    @Override
                    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

                    }
                }).circleCrop()
                .error(R.mipmap.error);
//                .priority(Priority.HIGH);
        Glide.with(context).load(file).apply(options).into(imageView);
    }

    public static String getVersionCode(Context context) {
        //获取包管理器
        PackageManager pm = context.getPackageManager();
        //获取包信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //返回版本号
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1.0";
    }

    public static String getSex(String status) {
        String str = "请选择性别";
        switch (status) {
            case "0":
                str = "保密";
                break;
            case "1":
                str = "男";
                break;
            case "2":
                str = "女";
                break;
        }
        return str;
    }

    /**
     * token
     *
     * @param context
     * @return
     */
    public static String getToken(Context context) {
        Object token = SharedPreferencesUtils.getParam(context, "access_token", "");
        if (token != null)
            return token.toString();
        return "";
    }

    /**
     * session
     *
     * @param context
     * @return
     */
    public static String getSession(Context context) {
        Object token = SharedPreferencesUtils.getParam(context, "session_id", "");
        if (token != null)
            return token.toString();
        return "";
    }

    /**
     * session
     *
     * @param context
     * @return
     */
    public static void setSession(Context context, String sid) {
        SharedPreferencesUtils.setParam(context, "session_id", sid);
    }

    /**
     * 得到shopTable
     *
     * @param context
     * @return
     */
    public static String getShopTable(Context context) {
        Object token = SharedPreferencesUtils.getParam(context, "shop_table", "");
        if (token != null)
            return token.toString();
        return "barbershop";
    }

    /**
     * @param context
     * @return
     */
    public static String getShopId(Context context) {
        Object token = SharedPreferencesUtils.getParam(context, "shop_id", "");
        if (token != null)
            return token.toString();
        return "";
    }

    private static ProgressDialog mProgressDialog;

    /**
     * @param stip
     */
    public static void showDiaLog(Context context, String stip) {
        if (mProgressDialog == null)
            mProgressDialog = ProgressDialog.show(context, "提示", stip + "...", true, true);
    }

    public static void dismissDiaLog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    private static CropOptions getCropOptions(int height, int width) {
//        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
//            builder.setWithOwnGallery(true);
//            builder.setCorrectImage(true);
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setWithOwnCrop(false);
        builder.setOutputX(width).setOutputY(height);
        builder.setAspectX(width).setAspectY(height);
        return builder.create();
    }

    /**
     * 文件
     *
     * @param takePhoto
     */
    public static void takeFromCapture(TakePhoto takePhoto, int height, int width) {
        String path = Environment.getExternalStorageDirectory() + "/temp/" + System.currentTimeMillis() + ".jpg";
        CommonConstant.takeImagePath = path;
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri = Uri.fromFile(file);
//        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
//        builder.setWithOwnGallery(true);
//        builder.setCorrectImage(true);
//        takePhoto.setTakePhotoOptions(builder.create());
//        LubanOptions option = new LubanOptions.Builder().setMaxHeight(height).setMaxWidth(width).create();
//        CompressConfig config = CompressConfig.ofLuban(option);
//        config.enableReserveRaw(false);
//        takePhoto.onEnableCompress(config, false);
        takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions(height, width));
    }


    /**
     * 拍照
     *
     * @param takePhoto
     * @param height
     * @param with
     */
    public static void takeFromDocuments(TakePhoto takePhoto, int height, int with) {
        String path = Environment.getExternalStorageDirectory() + "/temp/" + System.currentTimeMillis() + ".jpg";
        CommonConstant.takeImagePath = path;
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri = Uri.fromFile(file);
        takePhoto.onPickFromDocumentsWithCrop(imageUri, getCropOptions(height, with));
    }

    /**
     * 判断电话号码是否正确
     *
     * @param editText 控件名
     * @return
     */
    public static boolean isPhone(EditText editText) {
        if (!TextUtils.isEmpty(editText.getText())) {
            if (editText.getText().length() == 11) {
                return true;
            }
        }
        return false;
    }


    private static long lastClickTime = 0;

    public static boolean isclick() {
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastClickTime > 5) {
            lastClickTime = currentTime;
            return true;
        }
        return false;

    }

    /**
     * 生成32位md5码
     *
     * @param password
     * @return
     */
    public static String md5Password(String password) {

        try {
            // 得到一个信息摘要器
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(password.getBytes());
            StringBuffer buffer = new StringBuffer();
            // 把每一个byte 做一个与运算 0xff;
            for (byte b : result) {
                // 与运算
                int number = b & 0xff;// 加盐
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
            }

            // 标准的md5加密后的结果
            return buffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * ping
     *
     * @param ip
     * @return
     */
    public static boolean startPing(String ip) {
        try {
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 1 " + ip, null, null);
            int status = p.waitFor();
            if (status == 0) {
                return true;
            } else {
                return false;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            return false;
        }
    }
}
